# -*- coding: utf-8 -*-

from .img import *


def _get_vp8_size(data):
    w = int.from_bytes(data[26:28], byteorder='little')
    h = int.from_bytes(data[28:30], byteorder='little')
    return w, h


def _get_vp8l_size(data):
    # 文档见此：https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#2_riff_header
    w = (int.from_bytes(data[21:23], byteorder='little') & 0x3fff) + 1
    h = ((data[22] >> 6) | (data[23] << 2) | ((data[24] & 0xf) << 10)) + 1
    return w, h


def _get_vp8x_size(data):
    w = int.from_bytes(data[24:27], byteorder='little') + 1
    h = int.from_bytes(data[27:30], byteorder='little') + 1
    return w, h


_VP8_SIZE_GETTER = {
    'VP8 ': _get_vp8_size,
    'VP8L': _get_vp8l_size,
    'VP8X': _get_vp8x_size
}


class Webp(Img):
    __FORMAT__ = 'webp'

    @classmethod
    def size(cls, fobj):
        rb = fobj.read(1024)
        # 获取容器类型
        t = bytes(rb[12:16]).decode('utf-8')
        sg = _VP8_SIZE_GETTER.get(t)
        if not sg:
            return None
        w, h = sg(rb)

        return ImgSize(fobj.file_size, w, h)

    @classmethod
    def test(cls, fobj):
        rb = bytes(fobj.read(12))
        return rb[:4] == b'RIFF' and rb[-4:] == b'WEBP'
